package com.scwatch.core.fulltext;

import com.scwatch.common.fulltext.LuceneIndexTemplate;
import com.scwatch.core.constant.Constants;
import com.scwatch.core.domain.Node;
import com.scwatch.core.service.TaskService;
import org.hibernate.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import java.util.HashMap;
import java.util.Map;

/**
 * NodeFulltextDaoImpl
 * 
 * @author gjl
 * 
 */
@Repository
public class NodeFulltextDaoImpl implements NodeFulltextDao {
	public int addDocument(Integer siteId, Integer parentId,
			TaskService taskService, Integer taskId) {
		Session session = (Session) em.getDelegate();
		Map<String, Object> params = new HashMap<String, Object>();
		StringBuilder hql = new StringBuilder(
				"from Node bean where bean.site.id=:siteId and bean.parent.id=:parentId ");
        params.put("siteId",siteId);
        params.put("parentId",parentId);

		Query query = session.createQuery(hql.toString());
		query.setProperties(params);
		query.setCacheMode(CacheMode.IGNORE);
		ScrollableResults nodes = query.scroll(ScrollMode.FORWARD_ONLY);
		Node node;
		int count = 0;
		while (nodes.next() && taskService.isRunning(taskId)) {
			node = (Node) nodes.get(0);
            if(node!=null && node.getNodeModel().getFlag()!=null
                    && Constants.MODEL_FLAG_ANCHOR_LOOP_DYNAMICS.equals(node.getNodeModel().getFlag())){
                template.addDocument(FNode.doc(node));
            }
            taskService.add(taskId, 1);
            if (++count % 20 == 0) {
                session.flush();
                session.clear();
            }
		}
		return count;
	}

	private LuceneIndexTemplate template;

	@Autowired
	public void setLuceneIndexTemplate(LuceneIndexTemplate template) {
		this.template = template;
	}

	private EntityManager em;

	@javax.persistence.PersistenceContext
	public void setEm(EntityManager em) {
		this.em = em;
	}
}
